package com.iwhalecloud.bss.kite.cucc.web.controller.attr;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.iwhalecloud.bss.kite.client.api.attr.operate.IOperateInstMoreAttrService;
import com.iwhalecloud.bss.kite.client.api.attr.query.IQueryMoreAttrService;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneProdInstService;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneAccessProdInstService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.dto.spec.AttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IBusinessChangeService;
import com.iwhalecloud.bss.kite.cucc.service.scene.attr.CuccOperateInstAttrService;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module.ModifyInfoModuleHandler;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.ProdAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.scene.service.QuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.util.AcceptEngineUtil;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.common.util.StringUtil;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.core.util.JsonUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * add by ma.junjun 20210526
 * <>修正勾操作类型，前端直接调用核心包，没有进行个性化service_control_scope 过滤的问题 </>
 *  cs
 */
@RestController
@RequestMapping("/cuccSecondChangeProdAttr")
@Api(tags = {"/cuccProdAttr - 产品属性"})
public class CuccProdAttrController {

    @Autowired
    private IOperateSceneProdInstService operateSceneProdInstService;

    @Autowired
    private IQuerySceneAccessProdInstService querySceneProdInstService;

    @Autowired
    private IOperateInstMoreAttrService operateInstMoreAttrService;

    @Autowired
    private IQueryMoreAttrService queryMoreAttrService;

    @Autowired
    CuccOperateInstAttrService cuccOperateInstAttrService;

    @Autowired
    QuerySceneInstService querySceneInstService ;

    @Autowired
    private IBusinessChangeService businessChangeService;

    /**
     * <>更改：增加了个性过滤的逻辑 add by ma.junjun 20210526</>
     * @param sceneInstId
     * @param custId
     * @param fieldName
     * @param prodInstId
     * @param value
     * @param valueDesc
     * @param extJson
     * @param groupId
     * @return
     * @throws BaseAppException
     */
    @KiteTransactional
    @ApiOperation(value = "保存产品属性")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "sceneInstId", value = "场景id", required = false),
        @ApiImplicitParam(name = "custId", value = "客户id", required = false),
        @ApiImplicitParam(name = "fieldName", value = "产品属性规格编码", required = true),
        @ApiImplicitParam(name = "prodInstId", value = "产品实例标识", required = true),
        @ApiImplicitParam(name = "value", value = "产品属性值", required = true),
        @ApiImplicitParam(name = "valueDesc", value = "显示值", required = true)
    })
    @PostMapping
    public DataResult<List<ProdAttrVO>> saveProdAttr(@RequestParam(required = false) String sceneInstId, @RequestParam(required = false) String custId,
                                                     @RequestParam String fieldName, @RequestParam String prodInstId,
                                                     @RequestParam String value, @RequestParam String valueDesc, @RequestParam(required = false) String extJson,
                                                     @RequestParam(required = false) String groupId) throws BaseAppException {
        if (KiteStringUtils.isEmpty(extJson)) {
            AttrData data = new AttrData();
            data.setPage(true);
            extJson = JsonUtil.object2Json(data);
        }
        if(KiteStringUtils.isEmpty(sceneInstId)){
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        if(KiteStringUtils.isEmpty(custId)){
            custId = KiteWebContext.getContext().getCustId();
        }
        operateSceneProdInstService
            .updateProdInstAttr(sceneInstId, prodInstId, fieldName, value, valueDesc, custId, ContextUtil.getUserId().toString(), extJson);
        // 考虑属性联动改了其他值,返回所有最新的产品属性（临时方案）,如果传入属性组ID，根据属性组返回
        DataResult<List<ProdAttrVO>> result = this.listProdInstAttrs(prodInstId, groupId);

        // 临时方案，针对云专网的回刷不要了，需要回刷的都放在更多里面，点击更多会查询回来，大比武优化，加开关
        boolean flag = queryMoreAttrService.isNeedReflash(custId, prodInstId);
        if (flag) {
            AcceptEngineUtil.refreshScene(result);
        }
        return result;
    }

    @ApiOperation(value = "查询产品属性列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "prodId", value = "产品标识", required = true)})
    @GetMapping
    public DataResult<List<AttrDTO>> listProdAttrs(@RequestParam String prodId) {
        List<ProdAttr> prodAttrExtList = ProductCache.get(prodId).listProdAttrExts();
        List<AttrDTO> prodAttrList = new ArrayList<>();
        if (!KiteListUtils.isEmpty(prodAttrExtList)) {
            for (ProdAttr prodAttrExt : prodAttrExtList) {
                if (Objects.isNull(prodAttrExt.getShowType())) {
                    continue;
                }
                prodAttrList.add(KiteBeanUtils.transform(prodAttrExt, AttrDTO.class));
            }
        }
        return ErrorConsts.SUCCESS.getResult(prodAttrList);
    }

    @ApiOperation(value = "查询产品属性实例列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "prodInstId", value = "产品实例标识", required = true)})
    @GetMapping(value = "/inst")
    public DataResult<List<ProdAttrVO>> listProdInstAttrs(@RequestParam String prodInstId,
                                                          @RequestParam(required = false) String groupId) {
        List<ProdAttrVO> prodAttrList = new ArrayList<>();

        /**add by ma.junjun :过滤产品属性 begin 20210526**/
        String sceneInstId =KiteWebContext.getContext().getCurrentSceneInstId();
        //查询当前实例
        String custId =KiteWebContext.getContext().getCustId();

//        GoodsModifyInfoVO modifyInfo =modifyInfoModuleHandler.getProductChangeInfo(custId, sceneInstId, false);
//        List<ProductModuleVO> productModuleVOList=modifyInfo.getProduct();
//        prodAttrList = productModuleVOList.get(0).getProdRole().get(0).getProdAttr().getProdAttrList().stream().filter(it->KiteStringUtils.equals(it.getGroupId(),groupId)).collect(Collectors.toList());

        ProdAttrModuleVO prodAttrModuleVO=this.getProductChangeInfoNew(custId, sceneInstId,prodInstId);
        //根据分组筛选
        prodAttrList=prodAttrModuleVO.getProdAttrList().stream().filter(it->KiteStringUtils.equals(it.getGroupId(),groupId)).collect(Collectors.toList());;

        //物联网不需要更多展示功能
        String notShowMore = "2000957"; //默认值为物联网分类id

        String codea = DcPublicCache.getCodea("202012190001", "10000"); //配置不需要更多展示的分类id
        if (StringUtil.isNotEmpty(codea)) {
            notShowMore = codea;
        }
        String prodId = querySceneProdInstService.getProdInst(KiteWebContext.getContext().getCustId(),prodInstId).getProdId();
        String cateId = ProductCache.get(prodId).getCateId();
        if (cateId == null) {
            cateId = ProductCache.get(prodId).getProdSysNbr();
        }
        if (notShowMore.contains(cateId)) {
            for (ProdAttrVO attr : prodAttrList) {

                if (KeyConsts.PROD_ATTR_SHOW_TYPE_M.equals(attr.getShowType())) {
                    attr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
                }
            }
        }

        return ErrorConsts.SUCCESS.getResult(prodAttrList);
    }

    private ProdAttrModuleVO getProductChangeInfoNew(String custId,String sceneInstId, String prodInstId) {
        List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");//获取页面勾选的操作类型
        List<ProdAttrVO> prodAttrList = new ArrayList();
        ProdAttrModuleVO prodAttrModule = new ProdAttrModuleVO();
        KiteProdInst kiteProdInst = querySceneInstService.getProdInst(custId,prodInstId);
        ModifyInfoModuleHandler modifyInfoModuleHandler = SpringUtil.getBean(ModifyInfoModuleHandler.class);
        if(!KiteObjectUtils.isEmpty(kiteProdInst)){
            if (KiteListUtils.isNotEmpty(serviceOfferIdList)) {
                for (String serviceOfferId : serviceOfferIdList) {
                    prodAttrModule = businessChangeService
                        .dealProdAttrList(sceneInstId, custId, kiteProdInst, serviceOfferId, prodAttrModule);

                    if (KiteListUtils.isNotEmpty(prodAttrModule.getProdAttrList())) {
                        prodAttrList.addAll(prodAttrModule.getProdAttrList());
                    }
                }
                List<ProdAttrVO> prodAttrVOList = businessChangeService.removeProdAttrVO(prodAttrList); // 过滤去重
                prodAttrVOList.removeIf(attr -> KeyConsts.PROD_ATTR_SHOW_TYPE_H.equals(attr.getShowType()) || KeyConsts.PROD_ATTR_SHOW_TYPE_E.equals(attr.getShowType()));
                // 资料修正单部分属性必填、是否可编辑处理
                boolean flag = (KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.contains("1080"));
                prodAttrModule.setProdAttrList(modifyInfoModuleHandler.prodAttrConfig(sceneInstId, prodAttrVOList, flag));
                modifyInfoModuleHandler.addBusinessRemarkAttr(sceneInstId, prodAttrVOList, serviceOfferIdList, kiteProdInst);
                List<ProdAttrVO> newProdAttrList = prodAttrVOList.stream().filter(prodAttr ->
                KiteStringUtils.equals(prodAttr.getShowType(), KeyConsts.PROD_ATTR_SHOW_TYPE_D)).collect(Collectors.toList());
                if (KiteListUtils.isEmpty(newProdAttrList)) {
                    prodAttrVOList.forEach(attr ->{
                        if (KiteStringUtils.equals(attr.getShowType(), KeyConsts.PROD_ATTR_SHOW_TYPE_M)) {
                            attr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
                        }
                    });
                }
                prodAttrModule.setProdAttrList(prodAttrVOList);
            }else {
                // 通过bizType获取操作类型
                String serviceOfferIdListNew = querySceneInstService //通过bizType获取页面勾选的操作类型
                    .getExtParameterValue(sceneInstId, "bizType");
                if(KiteStringUtils.isNotEmpty(serviceOfferIdListNew)){
                    List<String> operateTypeList= Arrays.asList(KiteStringUtils.split(serviceOfferIdListNew,","));
                    for (String serviceOfferId : operateTypeList) {
                        prodAttrModule = businessChangeService
                            .dealProdAttrList(sceneInstId, custId, kiteProdInst, serviceOfferId, prodAttrModule);

                        if (KiteListUtils.isNotEmpty(prodAttrModule.getProdAttrList())) {
                            prodAttrList.addAll(prodAttrModule.getProdAttrList());
                        }
                    }
                }

                List<ProdAttrVO> prodAttrVOList = businessChangeService.removeProdAttrVO(prodAttrList); // 过滤去重
                prodAttrVOList.removeIf(attr -> KeyConsts.PROD_ATTR_SHOW_TYPE_H.equals(attr.getShowType()) || KeyConsts.PROD_ATTR_SHOW_TYPE_E.equals(attr.getShowType()));
                prodAttrModule.setProdAttrList(modifyInfoModuleHandler.prodAttrConfig(sceneInstId, prodAttrVOList, false));
                modifyInfoModuleHandler.addBusinessRemarkAttr(sceneInstId, prodAttrVOList, serviceOfferIdList, kiteProdInst);
                prodAttrModule.setProdAttrList(prodAttrVOList);
            }
        }

        return prodAttrModule;
    }

    @ApiOperation(value = "是否允许更多展示")
    @GetMapping(value = "/isAllowMore")
    public DataResult<Boolean> isAllowMore() {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        return ErrorConsts.SUCCESS.getResult(queryMoreAttrService.isShowMore(sceneInstId));
    }

    @KiteTransactional
    @ApiOperation(value = "异步处理新购更多属性", notes = "异步处理更多属性")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例标识", required = true)
    })
    @GetMapping("/affterMore")
    public DataResult<Boolean> initMoreAttrs(String sceneInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        return ErrorConsts.SUCCESS.getResult(operateInstMoreAttrService.initMoreAttrs(sceneInstId));
    }

    @KiteTransactional
    @ApiOperation(value = "异步处理迁转更多属性", notes = "异步处理更多属性")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例标识", required = true)
    })
    @GetMapping("/initMoreAttrsForTransfer")
    public DataResult<Boolean> initMoreAttrsForTransfer(String sceneInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        return ErrorConsts.SUCCESS.getResult(operateInstMoreAttrService.initMoreAttrsForTransfer(sceneInstId));
    }

    @ApiOperation(value = "查询更多产品属性实例列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "prodInstId", value = "产品实例标识", required = true)})
    @GetMapping(value = "/inst/more")
    public DataResult<List<ProdAttrVO>> listMoreProdInstAttrs(@RequestParam String prodInstId) {
        List<ProdAttrVO> prodAttrList = new ArrayList<>();
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        String custId = KiteWebContext.getContext().getCustId();
        List<InstAttrDTO> kiteAttrList = querySceneProdInstService
            .getPordInstAttrs(sceneInstId, custId, prodInstId, KeyConsts.PROD_ATTR_SHOW_TYPE_M).getResultObject();
        kiteAttrList.forEach(kiteAttr -> prodAttrList.add(KiteBeanUtils.transform(kiteAttr, ProdAttrVO.class)));
        return ErrorConsts.SUCCESS.getResult(prodAttrList);
    }

    @ApiOperation(value = "获取属性值")
    @ApiImplicitParams({@ApiImplicitParam(name = "prodInstId", value = "产品实例ID", required = true),
        @ApiImplicitParam(name = "fieldName", value = "字段名称", required = true)
    })
    @PostMapping("/prodInstAttr")
    public DataResult<String> queryProdInstAttr(@RequestParam String prodInstId, @RequestParam String fieldName) {
        DataResult<String> result = new DataResult<String>();
        String custId = KiteWebContext.getContext().getCustId();
        KiteProdInst prodInst = querySceneProdInstService.getProdInst(custId, prodInstId);
        List<KiteAttr> attrs = prodInst.listAttrs();
        for (KiteAttr attr : attrs) {
            if (KiteStringUtils.equals(fieldName, attr.getFieldName())) {
                result.setResultCode(KeyConsts.SUCCESS_0);
                result.setResultObject(attr.getValue());
                return result;
            }
        }
        result.setResultCode(KeyConsts.SUCCESS_0);
        result.setResultObject(null);
        return result;
    }


}
